<template>
  <div class="p-2">
    <!-- 添加或修改小程序类目信息对话框 -->
    <el-dialog :title="dialog.title" v-model="obj.visible" width="800px" append-to-body
      @update:model-value="appCategoryInfoDialog">
      <el-form ref="miniProgramCategoryFormRef" :model="form" :rules="rules" label-width="80px">
        <!-- 参数列表 start -->
        <el-table :data="tableData" style="width:100%" max-height="250">
          <el-table-column prop="categorySet" label="服务类目" width="!100%">
            <template #default="scope">
              <el-cascader v-model="scope.row.categorySet" :props="{ label: 'categoryName', value: 'categoryId' }"
                :options="categorySelectList" size="large" clearable
                @change="(val) => handleCascaderChange(val, scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="scope">
              <div v-if="scope.row.isNew">
                <el-button link type="success" size="small" @click="saveNewRow(scope.$index)">
                  保存
                </el-button>
                <el-button link type="danger" size="small" @click="cancelNewRow(scope.$index)">
                  取消
                </el-button>
              </div>
              <el-button v-else link type="danger" size="small" @click="deleteRow(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-4" style="width: 100%" @click="onAddItem">
          添加一行
        </el-button>
        <!-- 参数列表 end -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MiniProgramCategory" lang="ts">
import { listMiniProgramCategory, batchSave, delMiniProgramCategory, addMiniProgramCategory, updateMiniProgramCategory, wxCategorySelect } from '@/api/platform/miniProgramCategory';
import { MiniProgramCategoryVO, MiniProgramCategoryQuery, MiniProgramCategoryForm, WechatCategorySelectVO } from '@/api/platform/miniProgramCategory/types';

const obj = defineProps({
  baseId: {
    type: [String, Number], 
    default: undefined
  },
  title: {
    type: String,
    default: 'default message'
  },
  visible: {
    type: Boolean,
    required: true
  }
})

const _baseId = obj.baseId;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const miniProgramCategoryList = ref<MiniProgramCategoryVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const miniProgramCategoryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: true,
  title: ''
});

const initFormData: MiniProgramCategoryForm = {
  id: undefined,
  baseId: _baseId,
  categoryId: undefined,
  categoryClass: undefined,
  parentCategoryId: undefined,
  parentCategoryClass: undefined,
  level: undefined,
  status: undefined,
  remark: undefined,
  boList: []
}

const data = reactive<PageData<MiniProgramCategoryForm, MiniProgramCategoryQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    baseId: _baseId,
    categoryId: undefined,
    categoryClass: undefined,
    parentCategoryId: undefined,
    parentCategoryClass: undefined,
    level: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const emit = defineEmits(['update:visible'])
const appCategoryInfoDialog = (val: boolean) => {
  emit('update:visible', val)
}

/** 查询小程序类目信息列表 */
const getList = async () => {
  loading.value = true;
  console.log('queryParams',queryParams)
  const res = await listMiniProgramCategory(queryParams.value);
  console.log('res:',res)
  miniProgramCategoryList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 类目下拉 */
const categorySelectList = ref<WechatCategorySelectVO[]>([]) as any;

const getCategorySelect = async () => {
  const res = await wxCategorySelect(_baseId);
  categorySelectList.value = res.data;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  appCategoryInfoDialog(false)
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  miniProgramCategoryFormRef.value?.resetFields();
}

/** 提交按钮 */
const submitForm = () => {

  miniProgramCategoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      form.value.boList = tableData.value
        .filter(row => !row.isNew && row.categoryObject)
        .map(row => toRaw(row.categoryObject));
      if (form.value.boList.length === 0) {
        ElMessage.warning('请至少选择一个类目');
        buttonLoading.value = false;
        return;
      }
      const res = await batchSave(form.value);
      if (res.code !== 200) {
        ElMessage.error(res.msg);
        buttonLoading.value = false;
        return;
      } else {
        if (res.data) {
          ElMessage.success('操作成功');
          buttonLoading.value = false
          appCategoryInfoDialog(false)
          await getList();
        }
      }

    }
  });
}

// 递归查找完整的分类对象
const findCategoryById = (categories: any[], id: number): any | null => {
  for (const category of categories) {
    if (category.categoryId === id) {
      return category;
    }
    if (category.children) {
      const found = findCategoryById(category.children, id);
      if (found) return found;
    }
  }
  return null;
}

// 处理级联选择器变化
const handleCascaderChange = (value: any, index: number) => {
  const row = tableData.value[index];
  row.categorySet = value;
  const lastId = value[value.length - 1];

  if (lastId) {
    row.categoryObject = findCategoryById(categorySelectList.value, lastId);
  } else {
    row.categoryObject = null;
  }
}

// 参数列表 start
const tableData = ref<any[]>([])

const deleteRow = (index: number) => {
  tableData.value.splice(index, 1);
}

const onAddItem = () => {
  tableData.value.push({
    categorySet: [], // 初始化为空数组
    categoryObject: null, // 存储分类对象
    isNew: true // 标记为新行
  });
}

const saveNewRow = (index: number) => {
  const row = tableData.value[index];
  if (!row.categoryObject) {
    ElMessage.warning('请选择类目');
    return;
  }
  row.isNew = false;
  ElMessage.success('保存成功！');
}

const cancelNewRow = (index: number) => {
  tableData.value.splice(index, 1);
  ElMessage.info('已取消新增');
}

// 初始化表格数据
const initTableData = () => {
  tableData.value = miniProgramCategoryList.value.map((item) => {
    // 根据已有数据查找分类对象
    const categoryObject = findCategoryById(categorySelectList.value, Number(item.categoryId));

    return {
      categorySet: [],
      categoryObject: categoryObject,
      status: item.status,
      isNew: false
    };
  });
}

// 参数列表 end

onMounted(() => {
  getCategorySelect();
  getList().then(() => {
    // 数据加载完成后初始化表格
    initTableData();
  });
});
</script>